package com.ubi.core.framework.request;

import com.ubi.core.log.LogConstants;
import com.ubi.core.utils.ClassUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.mvc.ParameterizableViewController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class RequestContextInterceptor extends HandlerInterceptorAdapter {

    private RequestContext requestContext;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        requestContext.setActionName(getActionName(handler));
        requestContext.setRequestDate(new Date());
        MDC.put(LogConstants.MDC_ACTION, requestContext.getActionName());
        return true;
    }

    private String getActionName(Object handler) {
        if (handler instanceof HandlerMethod) {
            return String.format("%s-%s", ClassUtils.getSimpleOriginalClassName(((HandlerMethod) handler).getBean()),
                ((HandlerMethod) handler).getMethod().getName());
        } else if (handler instanceof ParameterizableViewController) {
            return ((ParameterizableViewController) handler).getViewName();
        }
        throw new IllegalStateException("unknown handler, handler=" + handler);
    }

    @Autowired
    public void setRequestContext(RequestContext requestContext) {
        this.requestContext = requestContext;
    }
}
